package com.lvmama.common.utils;

import com.lvmama.common.constants.Constants;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Hex;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

@Slf4j
public class EncodeUtil {
    /**
     * 密码加密
     * 
     * @param password 原密码
     * @return 加密后密码
     */
    public static String encodePassword(String password) {

        log.info("encodePassword start.");
        try {
            //MD5加密
            String algorithm = Constants.MD5;
            MessageDigest instance = MessageDigest.getInstance(algorithm);
            byte[] digest = instance.digest(password.getBytes());
            //十六进制加密
            char[] encodeHex = Hex.encodeHex(digest);
            return new String(encodeHex);
        } catch (NoSuchAlgorithmException e) {
            log.info("encodePassword algorithm name error:{}", e.getMessage(), e);
        } catch (Exception e) {
            log.info("encodePassword error:{}", e.getMessage(), e);
        }
        log.info("encodePassword end.");
        return null;
    }

    private static final String SALT = "lvmama";

    /**
     * 密码加密 （原sso中加密方法，项目中使用此方法对密码加密）
     * @param password
     * @return
     */
    public static String encode(String password) {
        password = password + SALT;
        MessageDigest md5 = null;
        try {
            md5 = MessageDigest.getInstance("MD5");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        char[] charArray = password.toCharArray();
        byte[] byteArray = new byte[charArray.length];

        for (int i = 0; i < charArray.length; i++)
            byteArray[i] = (byte) charArray[i];
        byte[] md5Bytes = md5.digest(byteArray);
        StringBuffer hexValue = new StringBuffer();
        for (int i = 0; i < md5Bytes.length; i++) {
            int val = ((int) md5Bytes[i]) & 0xff;
            if (val < 16) {
                hexValue.append("0");
            }

            hexValue.append(Integer.toHexString(val));
        }
        return hexValue.toString();
    }
}
